package sc.client.world;

import java.io.IOException;

import k8.SceneNode;

import sc.client.Client;
import sc.datainterchange.CodedInputBuffer;

public abstract class Container extends SceneNode
{	
	public Container parent;

	/**
	 * Creates an instance of Container.
	 */
	public Container()
	{
	}

	/**
	 * Gets the unique ID of the Container.
	 * 
	 * @return unique ID of the Container
	 */
	abstract public String getID();

	/**
	 * Receives "object" data and either creates or updates the corresponding
	 * object.
	 * 
	 * @param dataEvent
	 * @throws IOException 
	 */
	public void read(CodedInputBuffer codedinput) throws IOException
	{
		// Do we have a parent?
		if (codedinput.readBool())
		{	
			String type = codedinput.readString();
			String id = codedinput.readString();
			String key = type + id;
			
			// Check that the parent is known and place it inside the parent
			if (Client.containers.containsKey(key))
				Client.containers.get(key).add(this);
			else
				Client.logger.warning("Parent " + key + " of " + getID()
						+ " doesn't exist");
		}
		
		// Update the Objects position
		int x = codedinput.readSInt32();
		int y = codedinput.readSInt32();
		int z = codedinput.readSInt32();
		this.translate(-this.T[3], -this.T[7], -this.T[11]);
		this.translate(x / Client.SCALE, y / Client.SCALE, z / Client.SCALE);
	}

	/**
	 * Puts the specified Thing into this Containers contents.
	 * 
	 * If object already has a parent, it is first removed from its contents.
	 * 
	 * @param object
	 */
	public void add(Container object)
	{
		if (object.parent != null)
			Client.containers.get(object.parent.getID()).remove(object);
		object.parent = this;
		Client.containers.get(this.getID()).add(object);
	}

	/**
	 * Removes the specified Thing from this Objects contents.
	 * 
	 * @param object
	 */
	public void remove(Container object)
	{
		Client.containers.get(this.getID()).remove(object);
	}

	/**
	 * Returns the Tile container of this Thing.
	 * 
	 * @return the Tile container
	 */
	public Tile getTile()
	{
		int tilex = (int) ((this.T[3] - Tile.HALFWIDTH) 
				/ Tile.WIDTH) * Client.SCALE + Tile.HALFMAPSIZE;
		int tilez = (int) ((this.T[11] - Tile.HALFWIDTH)
				/ Tile.WIDTH) * Client.SCALE + Tile.HALFMAPSIZE;
		;
		return Tile.get(tilex, tilez);
	}

	@Override
	protected void transform()
	{
	}

}
